package mobi.greenplate.client.service;

import java.util.List;
import mobi.greenplate.client.connect.ConnectionContext;
import mobi.greenplate.client.connect.DefaultResponseHandler;
import mobi.greenplate.client.converter.AddressConverter;
import mobi.greenplate.client.domain.Address;
import mobi.greenplate.client.service.response.AddressListResponseHandler;
import mobi.greenplate.client.service.response.AddressResponseHandler;



/**
 *
 * @author dmakariev
 */
public class AddressService extends AbstractBaseService {

    public AddressService(ConnectionContext connectionContext) {
        super(connectionContext, "address");
		//throw new RuntimeException("buuum");
    }

    public void delete(Long id) {
        final int statusCodeDeleted = call().url(getUrlById(id)).delete(new DefaultResponseHandler());
        assertDeleted(statusCodeDeleted, id);
    }

    public Address save(final Address address) {
        final String stringEntity = AddressConverter.toXml(address);
        final DefaultResponseHandler defaultHandler = new DefaultResponseHandler();
        final Long id = address.getId();
        if (null == id) {
            //creating new
            final int statusCodeCreated = call().url(getServiceUrl()).stringEntity(stringEntity).post(defaultHandler);
            assertCreated(statusCodeCreated);
            //this is changing also the input parameter
            address.setId(defaultHandler.getId());
            return address;
        } else {
            //updating existing
            //for better performance is used the default handler and if the record is created is returned the same object
            //PUT acctually returns an xml which sould be processed with the concrete Handler
            final int statusCodeUpdated = call().url(getUrlById(id)).stringEntity(stringEntity).put(defaultHandler);
            assertExist(statusCodeUpdated, id);
            return address;
        }
    }

    public Address findById(Long id) {
        final AddressResponseHandler addressResponseHandler = new AddressResponseHandler();
        final int statusCode = call().url(getUrlById(id)).get(addressResponseHandler);

        assertExist(statusCode, id);

        final Address result = addressResponseHandler.getAddress();
        return result;
    }

    public List<Address> findAll(int firstResult, int maxResult) {

        final AddressListResponseHandler addressListResponseHandler = new AddressListResponseHandler();
        final String pagedUrl = getPagedUrl(firstResult, maxResult);
        final int statusCode = call().url(pagedUrl).get(addressListResponseHandler);

        assertExist(statusCode, pagedUrl);
        final List<Address> result = addressListResponseHandler.getAddressList();
        return result;
    }
}
